package cl.foursoft.daemon;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import cl.foursoft.daemon.properties.Propiedades;
import name.pachler.nio.file.*;

public class JPathWatcherApp {

	private String ruta = Propiedades.PATH_SOURCE;
	
	public void ejecutar(){
		WatchService watchService = FileSystems.getDefault().newWatchService();

		Path watchedPath = Paths.get(ruta);

		WatchKey key = null;
		try {
			key = watchedPath.register(watchService, StandardWatchEventKind.ENTRY_CREATE, StandardWatchEventKind.ENTRY_DELETE);
		} catch (UnsupportedOperationException uox){
			System.err.println("file watching not supported!");
			// handle this error here
		}catch (IOException iox){
			System.err.println("I/O errors");
			// handle this error here
		}

		for(;;){
			// take() will block until a file has been created/deleted
			WatchKey signalledKey;
			try {
				signalledKey = watchService.take();
			} catch (InterruptedException ix){
				// we'll ignore being interrupted
				continue;
			} catch (ClosedWatchServiceException cwse){
				// other thread closed watch service
				System.out.println("watch service closed, terminating.");
				break;
			}

			// get list of events from key
			List<WatchEvent<?>> list = signalledKey.pollEvents();

			// VERY IMPORTANT! call reset() AFTER pollEvents() to allow the
			// key to be reported again by the watch service
			signalledKey.reset();

			// we'll simply print what has happened; real applications
			// will do something more sensible here
			for(WatchEvent e : list){
				String message = "";
				if(e.kind() == StandardWatchEventKind.ENTRY_CREATE){
					Path context = (Path)e.context();
					message = context.toString() + " created";
					for(int temp=0; temp<500000;temp++){}
					enviarFicheros();
				} else if(e.kind() == StandardWatchEventKind.ENTRY_DELETE){
					Path context = (Path)e.context();
					message = context.toString() + " deleted";
				} else if(e.kind() == StandardWatchEventKind.OVERFLOW){
					message = "OVERFLOW: more changes happened than we could retreive";
				}
				System.out.println(message);
			}
		}
	}

	public void sendFile(String nombreArchivo){

		String nombreArchivoFinal;
		FileSystemResource fs;
		MultiValueMap<String, Object> parts;
		Boolean archivoResult;

		RestTemplate template = new RestTemplate();
		template.getMessageConverters().add(new FormHttpMessageConverter());
		template.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

		//enviarFicheros();

		//nombreArchivo = "test.png";
		nombreArchivoFinal = "test"+generarNombreBackup()+".txt";
		fs = new FileSystemResource(UtilImage.getAbsolutePath(nombreArchivo));
		parts = new LinkedMultiValueMap<String, Object>();
		parts.add("file", fs);
		parts.add("name", nombreArchivo);
		parts.add("final", nombreArchivoFinal);

		archivoResult = template.postForObject("http://localhost:8080/sensorDaemonServer/upload/file", parts, Boolean.class);
		System.out.println("GUARDAR ARCHIVO REGISTRO: "+archivoResult);

		if(archivoResult)
			eliminarFichero(nombreArchivo);
		else
			sendFile(nombreArchivo);
	}

	public void eliminarFichero(String nombre)
	{
		File f = new File(UtilImage.getAbsolutePath(nombre));
		f.delete();
		f.deleteOnExit();
	}

	public void enviarFicheros(){
		File dir = new File(ruta);

		String[] ficheros = dir.list();

		if (ficheros == null)
			System.out.println("No hay ficheros en el directorio especificado");
		else { 
			for (int x=0;x<ficheros.length;x++)
			{
				if(!ficheros[x].equalsIgnoreCase(".DS_Store"))
				{
					System.out.println(ficheros[x]);
					sendFile(ficheros[x]);
				}
			}
		}

	}

	public String generarNombreBackup(){
		Calendar cal = Calendar.getInstance();
		Date date = cal.getTime();
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
		return "-"+ format1.format(date);
	}
}
